<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true">
        <el-form-item>
          <el-input v-model="keyword" placeholder="请输入关键字..."></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getEmployees">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSave">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="employees" :cell-style="{'text-align':'center'}" :header-cell-style="{'text-align':'center'}"
              highlight-current-row v-loading="listLoading" @selection-change="selsChange"
              style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" label="序号" width="60">
      </el-table-column>
      <el-table-column prop="username" label="姓名" width="auto" sortable>
      </el-table-column>
      <el-table-column prop="phone" label="电话" width="auto" sortable>
      </el-table-column>
      <el-table-column prop="email" label="邮箱" width="auto" sortable>
      </el-table-column>
      <el-table-column prop="age" label="年龄" width="auto" sortable>
      </el-table-column>
      <el-table-column prop="department.name" label="部门" min-width="auto" sortable>
      </el-table-column>
      <el-table-column prop="shop.name" label="店铺" min-width="auto" sortable>
      </el-table-column>
      <el-table-column prop="state" label="状态" width="auto" sortable>
        <template scope="scope">
          <span v-if="scope.row.state=='0'" style="color: #ff0000">离职</span>
          <span v-if="scope.row.state=='1'" style="color: green">在职</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="auto">
        <template scope="scope">
          <el-button size="small" @click="handleSave(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="total, sizes, prev, pager, next, jumper"
                     @current-change="handleCurrentChange"
                     :page-size="pageSize"
                     :total="total"
                     :page-sizes="pageSizes"
                     @size-change="handleSizeChange"
                     :current-page="currentPage"
                     style="float:right;">
      </el-pagination>
    </el-col>

    <!--编辑/添加界面-->
    <el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="姓名" prop="username">
          <el-input v-model="saveForm.username" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="saveForm.phone" auto-complete="off" maxlength="11"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="saveForm.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="saveForm.state">
            <el-radio class="radio" :label="1">在职</el-radio>
            <el-radio class="radio" :label="0">离职</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input-number v-model="saveForm.age" :min="0" :max="200"></el-input-number>
        </el-form-item>
        <el-form-item label="部门">

          <!--回显的时候会将saveForm.manager_id的值跟下面managers中每个对象的id进行比对匹配上了就回显
          managers中对象的username-->
          <el-select v-model="saveForm.department_id" placeholder="请选择" clearable>

            <!--v-for="item in managers"-->
            <!--循环managers中的对象-->

            <!--:label="item.username"-->
            <!--回显的数据-->

            <!--:value="item.id"-->
            <!--添加修改时传到后端的数据-->

            <el-option
                v-for="item in departments"
                :label="item.name"
                :value="item.id">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.sn}}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="店铺">

          <!--回显的时候会将saveForm.manager_id的值跟下面managers中每个对象的id进行比对匹配上了就回显
          managers中对象的username-->
          <el-select v-model="saveForm.shop_id" placeholder="请选择" clearable>

            <!--v-for="item in managers"-->
            <!--循环managers中的对象-->

            <!--:label="item.username"-->
            <!--回显的数据-->

            <!--:value="item.id"-->
            <!--添加修改时传到后端的数据-->

            <el-option
                v-for="item in shops"
                :label="item.name"
                :value="item.id">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.tel}}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色">

          <!--回显的时候会将saveForm.manager_id的值跟下面managers中每个对象的id进行比对匹配上了就回显
          managers中对象的username-->
          <el-select v-model="saveForm.role_id" placeholder="请选择" clearable>

            <!--v-for="item in managers"-->
            <!--循环managers中的对象-->

            <!--:label="item.username"-->
            <!--回显的数据-->

            <!--:value="item.id"-->
            <!--添加修改时传到后端的数据-->

            <el-option
                v-for="item in roles"
                :label="item.name"
                :value="item.id">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.sn}}</span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>


  </section>
</template>

<script>


export default {
  data() {

    return {
      keyword: '',

      // 分页需要的参数
      employees: [],
      currentPage: 1,
      total: 0,
      pageSize: 5,
      listLoading: false,
      pageSizes: [5, 10, 20, 50],


      sels: [],//列表选中列

      saveFormVisible: false,//编辑界面是否显示
      saveLoading: false,
      saveFormRules: {
        username: [
          {required: true, message: '请输入姓名', trigger: 'blur'}
        ],
        phone: [
          {required: true, message: '请输入电话号码', trigger: 'blur'}
        ],
      },
      //编辑界面数据
      saveForm: {
        id: null,
        username: '',
        phone: '',
        email: '',
        age: '',
        state: '',
        department_id: '',
        shop_id: '',
        role_id: '',
      },

      title: '',

      shops: [],

      departments: [],

      roles: [],
    }
  },
  methods: {
    getRoles() {
      this.$http.get("/role").then(res => {
        this.roles = res.data;
      }).catch(res => {

      })
    },
    getShops() {
      this.$http.get("/shop").then(res => {
        this.shops = res.data;
      }).catch(res => {

      })
    },
    getDepartments() {
      this.$http.get("/department").then(res => {
        this.departments = res.data;
      }).catch(res => {

      })
    },
    //获取员工列表
    getEmployees() {
      let para = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        keyword: this.keyword,
      };
      this.listLoading = true;
      //NProgress.start();
      this.$http.post("/employee", para).then((res) => {
        this.total = res.data.totals;
        this.employees = res.data.data;
        this.listLoading = false;
        //NProgress.done();
      }).catch(res => {
        this.$message({
          duration: 1000,
          showClose: true,
          message: '系统繁忙，请稍后再试！',
          type: 'error'
        });
      });
    },


    handleCurrentChange(val) {
      this.currentPage = val;
      this.getEmployees();
    },

    handleSizeChange(val) {
      this.pageSize = val;
      this.getEmployees();
    },

    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {}).then(() => {
        let para = row.id;
        this.$http.delete("/employee/"+para).then(res => {
          if (res.data.success) {
            // 如果删除的数据是当前页的最后一条 删除后就显示当前数据的最后一页
            if ((this.total-1)%this.pageSize == 0 && this.currentPage == (this.total-1)/this.pageSize+1 && this.currentPage>1) {
              this.currentPage = this.currentPage - 1
            }
            this.getEmployees();
            this.$notify({
              title: '成功',
              duration: 2000,
              showClose: true,
              message: '删除成功！',
              type: 'success'
            });
          } else {
            this.$notify({
              title: '错误',
              duration: 2000,
              showClose: true,
              message: '系统繁忙(500)，请稍后再试！',
              type: 'error'
            });
          }
        }).catch(res => {
          this.$notify({
            title: '失败',
            duration: 2000,
            showClose: true,
            message: '系统繁忙(404/400)，请稍后再试！',
            type: 'error'
          });
        })


      }).catch(() => {

      });
    },
    //显示编辑界面
    handleSave: function (index, row) {
      this.getShops();
      this.getDepartments();
      this.getRoles();
      this.saveFormVisible = true;
      if (row == null) {
        this.title = "添加"
        this.saveForm = {
          id: null,
          username: '',
          phone: '',
          email: '',
          age: '',
          state: 1,
          department_id: '',
          shop_id: '',
          role_id: '',
        }
      } else {
        this.title = "修改"
        this.saveForm = Object.assign({}, row);
      }
    },

    //编辑
    saveSubmit: function () {
      this.$refs.saveForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.saveLoading = true;
            //NProgress.start();
            let para = Object.assign({}, this.saveForm);
            this.$http.put("/employee", para).then(res => {
              if (res.data.success) {
                this.saveFormVisible = false,//编辑界面是否显示
                this.saveLoading = false,
                this.getEmployees();
                this.$notify({
                  title: '成功',
                  duration: 2000,
                  showClose: true,
                  message: '操作成功！',
                  type: 'success'
                });

              } else {
                this.$notify({
                  title: '错误',
                  duration: 2000,
                  showClose: true,
                  message: '系统繁忙(500)，请稍后再试！',
                  type: 'error'
                });
              }
            }).catch(res => {
              this.$notify({
                title: '失败',
                duration: 2000,
                showClose: true,
                message: '系统繁忙(404/400)，请稍后再试！',
                type: 'error'
              });
            })
          }).catch(() => {

          });
        }
      });
    },

    selsChange: function (sels) {
      this.sels = sels;
    },
    //批量删除
    batchRemove: function () {
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        let para = {ids: ids};
        this.$http.patch("/employee",ids).then(res => {
          if (res.data.success) {
            // 如果删除的数据是当前页的最后一条 删除后就显示当前数据的最后一页
            if ((this.total - this.sels.length)%this.pageSize == 0 && this.currentPage == (this.total - this.sels.length)/this.pageSize+1 && this.currentPage >1) {
              this.currentPage = this.currentPage - 1
            }
            this.getEmployees();
            this.$notify({
              title: '成功',
              duration: 2000,
              showClose: true,
              message: '删除成功！',
              type: 'success'
            });
          } else {
            this.$notify({
              title: '错误',
              duration: 2000,
              showClose: true,
              message: '系统繁忙(500)，请稍后再试！',
              type: 'error'
            });
          }
        }).catch(res => {
          this.$notify({
            title: '失败',
            duration: 2000,
            showClose: true,
            message: '系统繁忙(404/400)，请稍后再试！',
            type: 'error'
          });
        })

      }).catch(() => {

      });
    }
  },
  mounted() {
    this.getEmployees();
  }
}

</script>

<style scoped>

</style>
